document.write("<script src='js/httpUtil.js'></script>");
document.write("<script src='js/common.js'></script>");
document.write("<script src='js/pagination.js'></script>");

var pageSize = 6;
var did;
var currentPage = 1;

$(document).ready(function () {
    departmentList(1);
});

$("#keywordBtn").click(function () {
    departmentList(1);
});

var layout = [
    { name: '机构名称', field: 'dname', headerClass: 'value_col', colClass: 'value_col', style: '' },
    { name: '机构描述', field: 'description', headerClass: 'value_col', colClass: 'value_col', style: ''},
    { name: '操作时间', field: 'opTime', headerClass: 'value_col', colClass: 'value_col', style: ''},
    { name: '子机构', treeNodes: true, headerClass: 'value_col', colClass: 'value_col', style: '' },
    {
        name: '操作',
        headerClass: 'value_col',
        colClass: 'value_col',
        style: 'width: 20%',
        render: function(row) {
            var department = JSON.parse(row);
            var editBtn = "<button class=\"btn btn-sm btn-primary m-b-5 m-t-5\" onclick='editDepartmentPanelBtn(" +department.id + ")'>编辑</button>"
            var enabledBtn = editBtn + " <button class=\"btn btn-sm btn-danger m-b-5 m-t-5\"" +
                "onclick='changeStatus(" + department.id + ",0)'>禁用</button>";
            if (department.enabled!=1) {
                enabledBtn = editBtn + " <button class=\"btn btn-sm btn-info m-b-5 m-t-5\" " +
                    "onclick='changeStatus(" + department.id + ",1)'>启用</button>";
            }
            enabledBtn = enabledBtn +
                " <button class=\"btn btn-sm btn-outline-danger m-b-5 m-t-5\" " +
                "onclick='deleteDepartment(" + department.id + ")'>删除</button>"

            return enabledBtn; //列渲染
        }
    },
];

function departmentList(currentPage) {
    this.currentPage = currentPage;
    $("#departmentList").empty()
    var keyword = $("#keyWord").val();
    var jsonObj = {"currentPage": currentPage, "pageSize": pageSize, "keyword": keyword};
    var result = httpPost(baseUrl + "/department/departmentList", jsonObj);
    if (result.flag == 1) {
        //  初始化分页插件
        pagination(result.result.total, pageSize, currentPage, callback)

        layui.use(['form', 'treetable', 'layer'], function() {
            var layer = layui.layer, form = layui.form, $ = layui.jquery;

            var tree = layui.treetable({
                elem: '#departmentList', //传入元素选择器
                spreadable: false, //设置是否全展开，默认不展开
                nodes: formatJson(result.result.list),
                layout: layout,
                callback: {
                    beforeCollapse : treetableBeforeCollapse,
                    onCollapse : treetableOnCollapse,
                    beforeExpand : treetableBeforeExpand,
                    onExpand : treetableOnExpand,
                }
            });

            function treetableBeforeCollapse(){
                return true;
            };
            function treetableOnCollapse(){
            };
            function treetableBeforeExpand(){
                return true;
            };
            function treetableOnExpand(){
            };

            form.render();
        });


    } else {
        toastr.error("系统错误", result.msg);
    }
}

function editDepartmentPanelBtn(did){
    var jsonObj = {"did": did};
    var result = httpPost(baseUrl + "/department/departmentDetail", jsonObj);
    if (result.flag==1){
        $("#editDID").val(result.result.did);
        $("#editDName").val(result.result.dname);
        $("#editDescription").val(result.result.description);
        enabledRadio("enabled",result.result.enabled)
        $("#editDepartModal").modal('show')
    }else{
        toastr.error("系统错误", result.msg);
    }
}

$("#editDepartBtn").click(function () {
    var did = $("#editDID").val();
    var dname =  $("#editDName").val();
    var description =  $("#editDescription").val();
    var enabled = $('[name=enabled]:checked').val();
    yorickAssert(did != "" && dname != "" && description != "", "请输入完整参数", "参数错误")
    var jsonObj = {
        "did":did,
        "dname":dname,
        "description":description,
        "enabled":enabled
    };
    var result = httpPost(baseUrl + "/department/editDepartment", jsonObj);
    if (result.flag==1){
        toastr.success("修改机构成功", "成功");
        $('#editDepartModal').modal('hide');
        departmentList(currentPage);
    }else{
        toastr.error("系统错误", result.msg);
    }
})

function changeStatus(did, enabled) {
    var jsonObj = {
        "did":did
    };
    var result = httpPost(baseUrl + "/department/departmentDetail", jsonObj);
    if(result.flag==1){
        var jsonObj = {
            "did":did,
            "dname":result.result.dname,
            "description":result.result.description,
            "enabled":enabled
        }
        var result = httpPost(baseUrl + "/department/editDepartment", jsonObj);
        if (result.flag == 1) {
            departmentList(currentPage);
        } else {
            toastr.error("系统错误", result.msg);
        }
    }else{
        toastr.error("系统错误", result.msg);
    }
}

function deleteDepartment(did){
    $("#deleteDID").val(did)
    $("#deleteDepartModal").modal('show')
}

$("#deleteDepartBtn").click(function () {
    var did = $("#deleteDID").val()
    var jsonObj = {
        "did":did
    };
    var result = httpPost(baseUrl + "/department/deleteDepartment", jsonObj);
    if (result.flag==1){
        toastr.success("删除机构成功", "成功");
        $("#deleteDepartModal").modal('hide')
        departmentList(currentPage);
    }else{
        toastr.error("系统错误", result.msg);
    }
})

function formatJson(json){
        for(var i=0;i<json.length;i++){
            json[i]["id"] = json[i]["did"];
            delete json[i]["did"];
            if(json[i].children!=null){
                json[i]["name"] = json[i].children[0]["dname"]+"..."
                json[i]["children"] = formatJson(json[i].children)
            }else{
                json[i]["name"] = "无"
            }
        }
        return json;
}

$("#addDepartPanelBtn").click(function () {
    $("#did").val(0);
    $("#dName").val("");
    $("#description").val("");
    $("#addDepartModal").modal('show')
})

$("#addDepartBtn").click(function () {
    var did = $("#did").val();
    var dname = $("#dName").val();
    var description = $("#description").val();
    yorickAssert(dname != "" && description != "", "请输入完整参数", "参数错误")
    var jsonObj = {
        "dname":dname,
        "description":description,
        "parentId":did
    };
    var result = httpPost(baseUrl + "/department/addDepartment", jsonObj);
    if (result.flag==1){
        toastr.success("新增机构成功", "成功");
        $('#addDepartModal').modal('hide');
        departmentList(1);
    }else{
        toastr.error("系统错误", result.msg);
    }
})

$("#addChildDepartPanelBtn").click(function (){
    var editDID = $("#editDID").val();
    $("#did").val(editDID);
    $("#dName").val("");
    $("#description").val("");
    $('#editDepartModal').modal('hide');
    $("#addDepartModal").modal('show');
})

function callback(targetPage, currentPage) {
    if (targetPage == 'prev') {
        departmentList(currentPage - 1);
    } else if (targetPage == 'next') {
        departmentList(currentPage + 1);

    }
}